//道路控制器
import { _decorator, Component, find, Prefab, Vec3, Node } from 'cc';
import { PlayerManager } from '../managers/PlayerManager';
import { RoadManager } from '../managers/RoadManager';
import { obstacleManager } from '../managers/ObstacleManager';

const { ccclass, property } = _decorator;
@ccclass('RoadController')
export class RoadController extends Component {
    @property(Prefab)
    private roadsPrefab: Prefab;

    @property(Prefab)
    private prefab1: Prefab;
    @property(Prefab)
    private prefab2: Prefab;
    @property(Prefab)
    private prefab3: Prefab;
    @property(Prefab)
    private prefab4: Prefab;

    @property(Node)
    player: Node;

    obstaclemanager: obstacleManager;
    thisroadName
    private playerManager: PlayerManager;
    private roadManager: RoadManager;

    private currentRoad;
    isMoving: Boolean;

    start() {
        this.obstaclemanager = obstacleManager.getInstance();
        this.roadManager = RoadManager.getInstance();
        this.playerManager = PlayerManager.getInstance();
        this.roadManager.setRoadControllerClass = this;

        let that = this;

        let prefab = [this.prefab1, this.prefab2, this.prefab3, this.prefab4]
        this.obstaclemanager.setobstaclePrefab(prefab)
        this.roadManager.initSetRoad(this.roadsPrefab, 4, this.node.worldPosition, this.node);

        this.initRoadName();

        let cycle = function () {
            setTimeout(() => {
                if (that.player.worldPosition.z > that.roadManager.currentroad[1].worldPosition.z) {
                    
                    if (that.roadManager) {
                        that.roadManager.setRoads();
                        //不断更新当前所在的位置
                        that.currentRoad = that.roadManager.currentroad[0];
                    }
                }
                cycle();
            }, 500);
        }
        cycle();
    }

    update(): void {
        if (this.isMoving) {
            let currentPosition = this.player.getWorldPosition().x;
            let leftNewPosition = this.roadManager.leftR ? this.roadManager.leftR.getWorldPosition().x : null;
            let rightNewPosition = this.roadManager.rightR ? this.roadManager.rightR.getWorldPosition().x : null;

            let positionGapl = Math.abs(currentPosition - leftNewPosition);
            let positionGapr = Math.abs(currentPosition - rightNewPosition);
            if (positionGapl < 0.3 || positionGapr < 0.3) {
                this.stopMovement();
                this.roadManager.setRoadName();
                this.roadManager.setIsMoving(false);
            }
        }
    }

    stopMovement() {
        this.playerManager.changePlayerSpeed()
    }

    setIsMoving(n) {
        this.isMoving = n;
        return this.isMoving;
    }

    initRoadName() {
        this.roadManager.RoadName = 'road';
        this.currentRoad = this.roadManager.currentroad[0];
        this.roadManager.setRoadName();
    }
}

